const gameBoard = document.getElementById('game-board');
const boardSize = 400;
const cellSize = 20;
const rows = boardSize / cellSize;
const cols = boardSize / cellSize;

let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: 0 };
let food = { x: 5, y: 5 };
let score = 0;

function draw() {
    gameBoard.innerHTML = '';
    snake.forEach(part => {
        const div = document.createElement('div');
        div.classList.add('snake-part');
        div.style.left = part.x * cellSize + 'px';
        div.style.top = part.y * cellSize + 'px';
        gameBoard.appendChild(div);
    });

    const foodDiv = document.createElement('div');
    foodDiv.classList.add('food');
    foodDiv.style.left = food.x * cellSize + 'px';
    foodDiv.style.top = food.y * cellSize + 'px';
    gameBoard.appendChild(foodDiv);
}

function moveSnake() {
    const head = { ...snake[0] };
    head.x += direction.x;
    head.y += direction.y;

    if (head.x === food.x && head.y === food.y) {
        score++;
        generateFood();
    } else {
        snake.pop();
    }

    if (head.x < 0 || head.x >= cols || head.y < 0 || head.y >= rows || snake.some(part => part.x === head.x && part.y === head.y)) {
        alert(`游戏结束！得分: ${score}`);
        resetGame();
        return;
    }

    snake.unshift(head);
    draw();
}

function changeDirection(event) {
    switch (event.key) {
        case 'ArrowUp':
            if (direction.y === 0) direction = { x: 0, y: -1 };
            break;
        case 'ArrowDown':
            if (direction.y === 0) direction = { x: 0, y: 1 };
            break;
        case 'ArrowLeft':
            if (direction.x === 0) direction = { x: -1, y: 0 };
            break;
        case 'ArrowRight':
            if (direction.x === 0) direction = { x: 1, y: 0 };
            break;
    }
}

function generateFood() {
    food = {
        x: Math.floor(Math.random() * cols),
        y: Math.floor(Math.random() * rows)
    };
}

function resetGame() {
    snake = [{ x: 10, y: 10 }];
    direction = { x: 0, y: 0 };
    score = 0;
    generateFood();
    draw();
}

document.addEventListener('keydown', changeDirection);

setInterval(moveSnake, 100);
resetGame();